<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-tabs stretch v-model="queryParams.status" :tab-change="handleQuery()">
            <el-tab-pane :name="2" label="待接单"></el-tab-pane>
            <el-tab-pane :name="3" label="已接单"></el-tab-pane>
            <el-tab-pane :name="4" label="派送中"></el-tab-pane>
            <el-tab-pane :name="5" label="已完成"></el-tab-pane>
            <el-tab-pane :name="6" label="已取消"></el-tab-pane>
            <el-tab-pane :name="7" label="退款"></el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="card-content" ref="cardRef">
      <template #header>
        <el-row :gutter="10" class="mb8" ref="headerRef">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:orders:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['customer:orders:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['customer:orders:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['customer:orders:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ordersList" :height="tableHeight" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" width="50" type="index" align="center">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="主键" align="center" prop="ordersId" min-width="200"/>
        <el-table-column label="订单状态" align="center" prop="status" min-width="80">
          <template #default="scope">
            <dict-tag :options="ta_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="用户名称" align="center" prop="address.consigneeName" min-width="150"/>
        <el-table-column label="地址" align="center" prop="address.addressName" :show-overflow-tooltip="true"
                         min-width="250"/>
        <el-table-column label="下单时间" align="center" prop="orderTime" width="200">

        </el-table-column>
        <el-table-column label="实收金额" align="center" prop="orderAmount">
          <template #default="scope">
            ￥ {{ scope.row.orderAmount }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" min-width="250"/>
        <!--        <el-table-column label="订单取消原因" align="center" prop="cancelReason"/>-->
        <!--        <el-table-column label="订单拒绝原因" align="center" prop="rejectionReason"/>-->
        <!--        <el-table-column label="订单取消时间" align="center" prop="cancelTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.cancelTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="预计送达时间" align="center" prop="estimatedDeliveryTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.estimatedDeliveryTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="配送状态" align="center" prop="deliveryStatus" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.deliveryStatus === 1" type="success">立即送出</el-tag>
            <el-tag v-else type="danger">选择具体时间</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="送达时间" align="center" prop="deliveryTime" width="200">
        </el-table-column>
        <el-table-column label="打包费" align="center" prop="packAmount" min-width="100"/>
        <el-table-column label="操作" fixed="right" align="center" min-width="180"
                         class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip  content="详情" placement="top">
              <el-button plain circle icon="view" @click="handleDetail(scope.row)"
                         v-hasPermi="['customer:orders:edit']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="queryParams.status===3" content="派送" placement="top">
              <el-button plain circle type="primary" @click="handleUpdate(scope.row)"
                         v-hasPermi="['customer:orders:edit']">
                <template #icon>
                  <svg-icon icon-class="dispatch"/>
                </template>
              </el-button>
            </el-tooltip>
            <el-tooltip v-if="queryParams.status===4" content="完成订单" placement="top">
              <el-button plain circle type="success" icon="select" @click="handleUpdate(scope.row)"
                         v-hasPermi="['customer:orders:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button plain circle type="danger" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['customer:orders:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <div class="page-content">
      <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改订单对话框 -->
    <el-drawer :title="drawer.title" v-model="drawer.visible" size="60%" append-to-body close-on-click-modal>
      <el-row class="mb-8">
        <el-col :span="18">
          <div class="flex gap-5">
            <el-text size="large">订单号</el-text>
            <el-text tag="b">{{ form.ordersId }}</el-text>
            <dict-tag :options="ta_order_status" :value="form.status"/>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="flex gap-5">
            <el-text>下单时间</el-text>
            <el-text tag="b">{{ form.orderTime }}</el-text>
          </div>
        </el-col>
      </el-row>
      <el-divider border-style="double"/>
      <div class="pl-10 pr-10 pt-5">
        <el-row>
          <el-col :span="16">
            <div class="flex gap-10 mb-5">
              <el-text>用户名:</el-text>
              <el-text>{{ form.address.consigneeName }}</el-text>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="flex gap-10">
              <el-text>手机号:</el-text>
              <el-text>{{ form.address.consigneePhone }}</el-text>
            </div>
          </el-col>
          <el-col>
            <div class="flex gap-10 mb-5">
              <el-text>地址:</el-text>
              <el-text>{{ form.address.addressName }}</el-text>
            </div>
          </el-col>
          <el-col>
            <div class="flex gap-10 mb-8">
              <el-text>备注:</el-text>
              <el-text>{{ form.remark }}</el-text>
            </div>
          </el-col>
          <el-col :span="3">
            <el-text>商品</el-text>
          </el-col>
          <el-col :span="21">
            <el-row>
              <el-col :span="12" v-for="(item,index) in form.goodsList">
                <div class="flex gap-10 mb-5">
                  <el-text>{{ item.goodsName }} X {{ item.number }}</el-text>
                  <el-text>￥ {{ item.amount }}</el-text>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="3">
            <el-text>费用</el-text>
          </el-col>
          <el-col :span="21">
            <el-text>合计</el-text>
            <el-text>￥ {{ form.orderAmount }}</el-text>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="form.status===2" :loading="buttonLoading" type="primary" @click="submitForm">接 单</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Orders" lang="ts">
import {listOrders, getOrders, delOrders, addOrders, updateOrders} from '@/api/customer/orders';
import {OrdersVO, OrdersQuery, OrdersForm} from '@/api/customer/orders/types';
import useSettingsStore from "@/store/modules/settings";
import {useTableHeight} from "@/utils/useTableHeight";

/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const {tableHeight} = useTableHeight(cardRef, [headerRef]);
const settingsStore = useSettingsStore()
const needTagsView = computed(() => settingsStore.tagsView);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {ta_order_status} = toRefs<any>(proxy?.useDict('ta_order_status'));
const ordersList = ref<OrdersVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const active = ref(1);

const queryFormRef = ref<ElFormInstance>();
const ordersFormRef = ref<ElFormInstance>();

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const initFormData: OrdersForm = {
  ordersId: undefined,
  status: undefined,
  userId: undefined,
  addressId: undefined,
  orderTime: undefined,
  checkoutTime: undefined,
  payMethod: undefined,
  payStatus: undefined,
  amount: undefined,
  remark: undefined,
  cancelReason: undefined,
  rejectionReason: undefined,
  cancelTime: undefined,
  estimatedDeliveryTime: undefined,
  deliveryStatus: undefined,
  deliveryTime: undefined,
  packAmount: undefined,
  tablewareNumber: undefined,
  tablewareStatus: undefined,
}
const data = reactive<PageData<OrdersForm, OrdersQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    status: 2,
    userId: undefined,
    addressId: undefined,
    orderTime: undefined,
    checkoutTime: undefined,
    payMethod: undefined,
    payStatus: undefined,
    amount: undefined,
    cancelReason: undefined,
    rejectionReason: undefined,
    cancelTime: undefined,
    estimatedDeliveryTime: undefined,
    deliveryStatus: undefined,
    deliveryTime: undefined,
    packAmount: undefined,
    tablewareNumber: undefined,
    tablewareStatus: undefined,
  },
  rules: {
    ordersId: [
      {required: true, message: "主键不能为空", trigger: "blur"}
    ],
    status: [
      {
        required: true,
        message: "订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款不能为空",
        trigger: "change"
      }
    ],
    userId: [
      {required: true, message: "用户id不能为空", trigger: "blur"}
    ],
    addressId: [
      {required: true, message: "地址id不能为空", trigger: "blur"}
    ],
    orderTime: [
      {required: true, message: "下单时间不能为空", trigger: "blur"}
    ],
    checkoutTime: [
      {required: true, message: "结账时间不能为空", trigger: "blur"}
    ],
    payMethod: [
      {required: true, message: "支付方式 1微信,2支付宝不能为空", trigger: "blur"}
    ],
    payStatus: [
      {required: true, message: "支付状态 0未支付 1已支付 2退款不能为空", trigger: "change"}
    ],
    amount: [
      {required: true, message: "实收金额不能为空", trigger: "blur"}
    ],
    remark: [
      {required: true, message: "备注不能为空", trigger: "blur"}
    ],
    cancelReason: [
      {required: true, message: "订单取消原因不能为空", trigger: "blur"}
    ],
    rejectionReason: [
      {required: true, message: "订单拒绝原因不能为空", trigger: "blur"}
    ],
    cancelTime: [
      {required: true, message: "订单取消时间不能为空", trigger: "blur"}
    ],
    estimatedDeliveryTime: [
      {required: true, message: "预计送达时间不能为空", trigger: "blur"}
    ],
    deliveryStatus: [
      {required: true, message: "配送状态  1立即送出  0选择具体时间不能为空", trigger: "change"}
    ],
    deliveryTime: [
      {required: true, message: "送达时间不能为空", trigger: "blur"}
    ],
    packAmount: [
      {required: true, message: "打包费不能为空", trigger: "blur"}
    ],
    tablewareNumber: [
      {required: true, message: "餐具数量不能为空", trigger: "blur"}
    ],
    tablewareStatus: [
      {required: true, message: "餐具数量状态  1按餐量提供  0选择具体数量不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrders(queryParams.value);
  ordersList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  ordersFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  console.log(queryParams.value.status);
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrdersVO[]) => {
  ids.value = selection.map(item => item.ordersId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  drawer.visible = true;
  drawer.title = "添加订单";
}

/*订单详情操作*/
const handleDetail = async (row?: OrdersVO) => {
  const _ordersId = row?.ordersId || ids.value[0]
  const res = await getOrders(_ordersId);
  Object.assign(form.value, res.data);
  drawer.visible = true;
  drawer.title = "订单详情";
}

/*修改订单状态*/
const handleUpdate = async (row?: OrdersVO) => {
  const _ordersId = row?.ordersId || ids.value[0]
  const res = await getOrders(_ordersId);
  Object.assign(form.value, res.data);
  form.value.status = queryParams.value.status + 1;
  await updateOrders(form.value);
  await getList();
}

/** 接单按钮 */
const submitForm = async () => {
  buttonLoading.value = true;
  form.value.status = '3';
  if (form.value.ordersId) {
    await updateOrders(form.value).finally(() => buttonLoading.value = false);
  }
  proxy?.$modal.msgSuccess("操作成功");
  drawer.visible = false;
  await getList();
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrdersVO) => {
  const _ordersIds = row?.ordersId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单编号为"' + _ordersIds + '"的数据项？').finally(() => loading.value = false);
  await delOrders(_ordersIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('customer/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

